package io.renren.modules.sys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.CarOrderinfo;
import io.renren.modules.sys.entity.Carmanage;
import io.renren.modules.sys.entity.dto.*;
import io.renren.modules.sys.service.CarOrderinfoService;
import io.renren.modules.sys.service.CarmanageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author beisheng
 * @since 2022-09-05
 */
@RestController
@CrossOrigin
@RequestMapping("/CarOrderinfo")
public class CarOrderinfoController {
    @Autowired
    private CarOrderinfoService carOrderinfoService;
    @Autowired
    private CarmanageService carmanageService;
    @Autowired
    JavaMailSenderImpl mailSender;

    public R getEmailCode(String email,String test) throws MessagingException {
        int count=1;//默认发送一次
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        while(count--!=0){
            //标题
            helper.setSubject("神州租车提示您");
            //内容
            helper.setText(test,true);
            //邮件接收者
            helper.setTo(email);
            //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
            helper.setFrom("1791201652@qq.com");
            mailSender.send(mimeMessage);
            System.out.println("邮件发送成功！"+(count+1));
        }
        return R.ok();
    }

    @Transactional
    @RequestMapping("/insert")
    public R insert(@RequestBody DingdanDto dto){
        CarOrderinfo carOrderinfo = new CarOrderinfo();
        Carmanage carmanage = new Carmanage();
        BeanUtils.copyProperties(dto,carOrderinfo);
        carOrderinfo.setUpdateTime(new Date());
        carOrderinfo.setDelFlag(0);
        carOrderinfo.setCreateTime(new Date());
        carOrderinfo.setExplaininfo("6666");
        carOrderinfoService.save(carOrderinfo);
        carmanage.setId(dto.getCarId());
        carmanage.setCarStatus("n");
        carmanageService.updateById(carmanage);
        return R.ok();
    }
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) throws ParseException {

        PageUtils list = carOrderinfoService.listAll1(params);
        return R.ok().put("list",list);
    }

    @RequestMapping("/findAll")
    public List<CarOrderinfo> findAll(){
        List<CarOrderinfo> list = carOrderinfoService.list(new QueryWrapper<CarOrderinfo>().eq("del_flag",0));
        return list;
    }
    @RequestMapping("/list1")
    public R list1(@RequestParam Map<String, Object> params) throws ParseException {

        PageUtils list = carOrderinfoService.listAll(params);
        return R.ok().put("list",list);
    }
    @RequestMapping("/okPrese")
    public R okPrese(@RequestParam Map<String,Object> params){
        String status = (String) params.get("status");
        String id = (String) params.get("id");
        CarOrderinfo carOrderinfo = new CarOrderinfo();
        carOrderinfo.setStatus(Integer.valueOf(status));
        carOrderinfoService.update(carOrderinfo,new QueryWrapper<CarOrderinfo>().eq("id",id));
        return R.ok();
    }

    @RequestMapping("/updateStatus/{id}")
    public R updateStatus(@PathVariable("id")Integer id){
        CarOrderinfo carOrderinfo = new CarOrderinfo();
        carOrderinfo.setStatus(5);
        carOrderinfo.setId(id);
        carOrderinfoService.updateById(carOrderinfo);
        return R.ok();
    }

    @RequestMapping("/getEmailCode")
    public R getEmailCode(@RequestBody EmailUserDto emailUserDto) throws MessagingException {
        int count=1;//默认发送一次
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        while(count--!=0){
            //标题
            helper.setSubject("神州租车");
            //内容
            helper.setText("您好！神州租车提示您,"+emailUserDto.getMessage(),true);
            //邮件接收者
            helper.setTo(emailUserDto.getUserEmail());
            //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
            helper.setFrom("1791201652@qq.com");
            mailSender.send(mimeMessage);
            System.out.println("邮件发送成功！"+(count+1));
        }
        return R.ok();
    }
    @RequestMapping("/selByStatus")
    public R selByStatus(@RequestBody userDingdanDto userDingdanDto){
        String root = userDingdanDto.getRoot();
        Integer status = userDingdanDto.getStatus();
        Integer userId = userDingdanDto.getUserId();
        QueryWrapper<CarOrderinfo> queryWrapper = new QueryWrapper<>();
        if(!root.equals(null) && !root.equals("")){
            queryWrapper.like("car_name",root).or().eq("order_id",root);
        }
        if(status!=null){
            queryWrapper.eq("status",status);
        }
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("del_flag",0);
        List<CarOrderinfo> list = carOrderinfoService.list(queryWrapper);
        return R.ok().put("list",list);

    }
    @RequestMapping("/update")
    public R update(@RequestBody dingUpdateDto dingUpdateDto){
        CarOrderinfo carOrderinfo = new CarOrderinfo();
        BeanUtils.copyProperties(dingUpdateDto,carOrderinfo);
        carOrderinfoService.updateById(carOrderinfo);
        return R.ok();
    }
    @Transactional
    @RequestMapping("/updateOrderAndCar")
    public R updateOrderAndCar(@RequestBody updateOrderAndCarDto carDto){
        CarOrderinfo carOrderinfo = new CarOrderinfo();
        Carmanage carmanage = new Carmanage();
        carmanage.setId(carDto.getCarId());
        BeanUtils.copyProperties(carDto,carOrderinfo);
        carOrderinfo.setDelFlag(1);
        carmanage.setCarStatus("y");
        carOrderinfoService.updateById(carOrderinfo);
        carmanageService.updateById(carmanage);
        return R.ok();
    }
    @RequestMapping("/test")
    public void test(){
        // 创建任务队列   10 为线程数量
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        // 执行任务
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            List<CarOrderinfo> list = null;
            list = this.findAll();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            Date date1 = null;
            Date date2 = null;

            for (CarOrderinfo carOrderinfo : list) {
                try {
                    date1 = sdf.parse(sdf.format(date));
                    date2 = sdf.parse(sdf.format(carOrderinfo.getUseTime()));

                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(date2.getTime()<date1.getTime()){
                    String test = "您好！神州租车提示您。您的租车订单已逾期,订单号:"+carOrderinfo.getOrderId()+"请按时归还";

                    try {
                        this.getEmailCode(carOrderinfo.getUserEmail(),test);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        date1 = sdf.parse(sdf.format(date));
                        date2 = sdf.parse(sdf.format(carOrderinfo.getUseTime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Long num = date2.getTime() - date1.getTime();
                    System.out.println(num/24/60/60/1000);
                    long text = num/24/60/60/1000;
                    if(text<=4 && text>=1){
                        String test = "您好！神州租车提示您。您的租车订单还剩"+text+"天就逾期了，记得按时归还";
                        try {
                            this.getEmailCode(carOrderinfo.getUserEmail(),test);
                        } catch (MessagingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, 0, 3, TimeUnit.DAYS); // 每 3天 执行一次
    }
}

